package com.hd.crdao.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.activity.ReleaseActivity;
import com.hd.crdao.adapter.MyCarSourceAdapter;
import com.hd.crdao.bean.CarInfoListBean;
import com.hd.crdao.bean.MyCarSourceBean;
import com.hd.crdao.config.Config;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.MyListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 *
 *@author Programming
 *@date 2017/6/6 0006
 */

public abstract class MyCarSourceBaseFragment extends Fragment {
    @BindView(R.id.mycarsourcelist)
    MyListView mMycarsourceList;
    @BindView(R.id.progreassbar)
    ProgressBar mProgreassbar;
    @BindView(R.id.progreassbar_layout)
    RelativeLayout mProgreassbarLayout;
    @BindView(R.id.load_state)
    TextView mLoadState;

    public MyCarSourceAdapter mMyCarSourceAdapter;
    public MyCarSourceBean mMyCarSourceBean;
    public List<CarInfoListBean> mCarInfoList;
    public int listSize;
    private Handler mhandler = new Handler();
    private boolean allSelected = false;
    @BindView(R.id.added_carsource)
    Button mAddedCarsource;
    @BindView(R.id.delete_carsource)
    Button mDeleteCarsource;

    /**
     * 对我的车源进行三种操作(上架 下架 删除)
     */
    public static final String DELETE = "0";
    public static final String ADD = "1";
    public static final String REMOVE = "2";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mystore, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        initButton();
        initData();
        if ("1".equals(setState())) {       //已上架
            initButton();
            mDeleteCarsource.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    ALog.d(toTransferString(mMyCarSourceAdapter.ids));
                    Handlde(toTransferString(mMyCarSourceAdapter.ids), REMOVE);

                }
            });
            mDeleteCarsource.setBackgroundResource(R.drawable.mainbutton_selector);
            mDeleteCarsource.setTextColor(Color.WHITE);
        } else if ("2".equals(setState())) {                //仓库
            mDeleteCarsource.setVisibility(View.VISIBLE);
            mAddedCarsource.setVisibility(View.VISIBLE);
            mAddedCarsource.setBackgroundResource(R.drawable.mainbutton_selector);
            mAddedCarsource.setText("上架");

            mAddedCarsource.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ids = toTransferString(mMyCarSourceAdapter.ids);
                    ALog.d(ids);
                    Handlde(ids, ADD);
                }
            });
            mDeleteCarsource.setText("删除");
            mDeleteCarsource.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ids = toTransferString(mMyCarSourceAdapter.ids);
                    ALog.d(ids);
                    Handlde(ids, DELETE);
                }
            });
            mDeleteCarsource.setBackgroundResource(R.drawable.delete_button_selector);
        } else {        //草稿
            mAddedCarsource.setVisibility(View.GONE);
            mDeleteCarsource.setVisibility(View.VISIBLE);
            mDeleteCarsource.setText("删除");
            mDeleteCarsource.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String ids = toTransferString(mMyCarSourceAdapter.ids);
                    ALog.d(ids);
                    Handlde(ids, DELETE);
                }
            });
            mDeleteCarsource.setBackgroundResource(R.drawable.mainbutton_selector);
            mDeleteCarsource.setTextColor(Color.WHITE);
        }
        mMycarsourceList.setonRefreshListener(new MyListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mhandler.postDelayed(new DisPlayRunnable(), 1500);

            }
        });


        mMycarsourceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position = position - 1;
                ALog.d("我的车源条目被点击");
                CarInfoListBean carInfoListBean = mCarInfoList.get(position);
                Intent intent = new Intent(UIUtils.getContext(), ReleaseActivity.class);
                intent.putExtra("carid", carInfoListBean.getId());
                intent.putExtra("isFromMain", false);
                intent.putExtra("state", setState());
                startActivity(intent);
            }
        });
    }


    private void initData() {
        ALog.d("初始化数据");
        String businessid = SPUtils.getString(Config.businessId, "");
        OkHttpUtils.post().url(Constants.FINDCARINFOLIST_URL)
                .addParams("appFlag", "true")
                .addParams("id", businessid)
                .addParams("state", setState()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("网络开了个小差");
                mProgreassbarLayout.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                // ALog.d(response);
                mMyCarSourceBean = new Gson().fromJson(response, MyCarSourceBean.class);
                if ("00".equals(mMyCarSourceBean.getSuccess())) {
                    mCarInfoList = mMyCarSourceBean.getCarInfoList();
                    listSize = mCarInfoList.size();//就长度赋值
                    mMyCarSourceAdapter = new MyCarSourceAdapter(mCarInfoList, setState());
                    mMycarsourceList.setAdapter(mMyCarSourceAdapter);
                    mProgreassbarLayout.setVisibility(View.GONE);
                } else {
                    mProgreassbarLayout.setVisibility(View.VISIBLE);
                    mLoadState.setText(mMyCarSourceBean.getMessage());
                }

            }
        });


    }

    private void initButton() {
        mAddedCarsource.setVisibility(View.GONE);
        mDeleteCarsource.setVisibility(View.VISIBLE);
        mDeleteCarsource.setText("下架");
    }

    public abstract String setState();


    public void AllSelected() {

       /* ALog.d("全选方法执行了么");
        // 遍历list的长度，将已选的设为未选，未选的设为已选
        for (int i = 0; i < listSize; i++) {
            mMyCarSourceAdapter.list.add(i, !allSelected);
        }*/
        mMyCarSourceAdapter.selectAll(allSelected);
        allSelected = !allSelected;
    }


    private class DisPlayRunnable implements Runnable {
        @Override
        public void run() {
            initData();
            mMyCarSourceAdapter.notifyDataSetChanged();
            mProgreassbarLayout.setVisibility(View.GONE);
            mMycarsourceList.onRefreshComplete();
        }
    }


    public String toTransferString(String[] ids) {

        StringBuilder sb = new StringBuilder();
        if (ids != null) {
            for (String objStr : ids) {
                if (objStr != null) {
                    sb.append(objStr).append(",");
                }
            }
            int len = sb.length();
            if (len > 0) {
                sb.deleteCharAt(len - 1);
            }
        }
        return sb.toString();
    }


    /**
     * 对我的车源进行三种上架 下架 删除操作
     *
     * @param doWhat 操作指示
     */
    public void Handlde(String ids, String doWhat) {
        OkHttpUtils.post().url(Constants.UPDATECARINFOLIST_URL)
                .addParams("appFlag", "true")
                .addParams("ids", ids)
                .addParams("handle", doWhat)
                .addParams("sign", Constants.SIGN)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("服务器连接异常");
            }

            @Override
            public void onResponse(String response, int id) {
                mProgreassbarLayout.setVisibility(View.VISIBLE);
                mhandler.postDelayed(new DisPlayRunnable(), 1200);

            }
        });

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            initData();
        }
    }


}

